import { Controller, UseGuards, Req, UnauthorizedException } from '@nestjs/common';
import { Crud, CrudAuth ,CrudController, CrudRequest, Override, ParsedRequest, ParsedBody, CreateManyDto } from "@nestjsx/crud";
import { User } from "../../entities/user.entities";
import { UserService } from "../../services/user/user.service";
import { ApiTags, ApiResponse, ApiQuery, ApiBody,ApiBearerAuth} from '@nestjs/swagger';
import { password } from "../../utils/_crypto";
import { AuthGuard } from '@nestjs/passport';
import { Request } from 'express';
import { identity } from 'rxjs';

@Crud({
  model:{
    type: User
  },
  query:{
    join:{
      userLevel:{
        exclude:[]
      },
      address:{
        exclude:["user_id"]
      },
      order:{
        exclude:["user_id","shipping_id","coupon_id","parent_id"]
      },
      userCoupon:{
        exclude:[]
      },
      'userCoupon.coupon':{
        exclude:[]
      }
    },
    exclude: ['weixin_openid','password',"email_token","email_token_exptime","last_login_ip","last_login_time","register_time","register_ip"],
    persist:['username','mobile']
  },
  routes:{
    only:['createOneBase','updateOneBase','getOneBase','getManyBase']
  }

})
@ApiTags('user')
@Controller('api/user')
export class UserController implements CrudController<User>{
  constructor(
    public service:UserService
  ){}

  get base(): CrudController<User> {
    return this;
  }

  @ApiBody({
    type: User
  })
  @Override()
  createOne(
    @ParsedRequest() req: CrudRequest,
    @ParsedBody() dto: User,
    @Req() reqs:Request  
  ): Promise<User> {
    dto.password = password(dto.password);
    dto.register_ip=reqs.ip;
    //console.log(dto);
    return this.base.createOneBase(req, dto);
  }

  @ApiBody({
    type: User
  })
  @UseGuards(AuthGuard('jwt'))
  @ApiBearerAuth()
  @Override()
  updateOne(
    @ParsedRequest() req: CrudRequest,
    @ParsedBody() dto: User): Promise<User>{
    dto.password = password(dto.password);
    return this.base.updateOneBase(req,dto);
  }

  @UseGuards(AuthGuard('jwt'))
  @ApiBearerAuth()
  @Override()
  async getOne(
    @ParsedRequest() req: CrudRequest,
    @Req() reqs  
  ): Promise<User> {
    //console.log(req.parsed.paramsFilter);
    //console.log(reqs.user);
    if(reqs.user.userId!=req.parsed.paramsFilter[0].value){
      throw new UnauthorizedException();
    }
    const result=await this.base.getOneBase(req);
    return result
  }

  @UseGuards(AuthGuard('jwt'))
  @ApiBearerAuth()
  @Override()
  async getMany(
    @ParsedRequest() req: CrudRequest,
    @Req() reqs  
  ) {
    //console.log(req.parsed.paramsFilter);
    //console.log(reqs.user);
    req.options.query.filter=[{
      field: 'id',
      operator: '$eq',
      value: reqs.user.userId
    }];
    const result=await this.base.getManyBase(req);
    return result
  }
}
